//
//  LYIDFAManager.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/8/4.
//

import AppTrackingTransparency
import AdSupport

final class LYIDFAManager {
    
    static let shared = LYIDFAManager()
    private init() {}
    
    // MARK: - Public Methods
    
    /// 请求广告追踪权限并返回 IDFA
    func requestTrackingAuthorization(completion: @escaping (String?) -> Void) {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { [weak self] status in
                self?.handleAuthorizationStatus(status, completion: completion)
            }
        } else {
            // iOS 13 及以下直接检查是否允许广告追踪
            let isEnabled = ASIdentifierManager.shared().isAdvertisingTrackingEnabled
            completion(isEnabled ? getIDFA() : nil)
        }
    }
    
    /// 获取当前 IDFA（不触发权限弹窗）
    func getCurrentIDFA() -> String? {
        if #available(iOS 14, *) {
            guard ATTrackingManager.trackingAuthorizationStatus == .authorized else {
                return nil
            }
        } else {
            guard ASIdentifierManager.shared().isAdvertisingTrackingEnabled else {
                return nil
            }
        }
        return getIDFA()
    }
    
    /// 检查广告追踪权限状态
    func isAdvertisingTrackingEnabled() -> Bool {
        if #available(iOS 14, *) {
            return ATTrackingManager.trackingAuthorizationStatus == .authorized
        } else {
            return ASIdentifierManager.shared().isAdvertisingTrackingEnabled
        }
    }
    
    // MARK: - Private Methods
    
    /// 处理 iOS 14+ 的授权状态（仅 iOS 14+ 可用）
    @available(iOS 14, *)
    private func handleAuthorizationStatus(
        _ status: ATTrackingManager.AuthorizationStatus,
        completion: @escaping (String?) -> Void
    ) {
        DispatchQueue.main.async {
            switch status {
            case .authorized:
                completion(self.getIDFA())
            case .denied, .restricted, .notDetermined:
                completion(nil)
            @unknown default:
                completion(nil)
            }
        }
    }
    
    /// 直接获取 IDFA（不检查权限）
    func getIDFA() -> String {
        return ASIdentifierManager.shared().advertisingIdentifier.uuidString
    }
}
